#!/usr/bin/php -d mysqlnd.net_read_timeout=3600
<?
set_include_path("../../../include");
require("header.inc.php");

$startShard = !empty($argv[1]) ? $argv[1] : 1;

$shardIDs = Zotero_DB::columnQuery("SELECT shardID FROM shards WHERE shardID >= ? ORDER BY shardID", $startShard);
foreach ($shardIDs as $shardID) {
	echo "Shard: $shardID\n";
	
	$rows = Zotero_DB::query(
		"SELECT libraryID, itemID FROM items JOIN publicationsItems USING (itemID) "
		. "WHERE libraryID IN (SELECT libraryID FROM shardLibraries WHERE libraryType='group') ORDER BY libraryID, itemID",
		false,
		$shardID
	);
	$lastLibraryID = null;
	foreach ($rows as $row) {
		echo "Found bad item " . $row['itemID'] . "\n";
		Zotero_DB::query("DELETE FROM publicationsItems WHERE itemID=?", $row['itemID'], $shardID);
		
		// If done with a library, update its version
		if ($lastLibraryID && $row['libraryID'] != $lastLibraryID) {
			echo "Updating library " . $row['libraryID'] . "\n";
			Zotero_DB::query("UPDATE shardLibraries SET version=version+1 WHERE libraryID=?", $lastLibraryID, $shardID);
		}
		$lastLibraryID = $row['libraryID'];
	}
	if ($lastLibraryID) {
		echo "Updating library $lastLibraryID\n";
		Zotero_DB::query("UPDATE shardLibraries SET version=version+1 WHERE libraryID=?", $lastLibraryID, $shardID);
	}
}
